﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Money.Data;
using Money.Interfaces;
using One.Framework;

public partial class UserControls_TreeCategories : System.Web.UI.UserControl
{
    private string categoryName;
    public string CategoryName 
    {
        get
        {
            return hdCategoryName.Value;
        }
        set
        {
            this.categoryName = value;
        }
    }

    public TextBox TextBoxName
    {
        get
        {
            return this.tbCategory;
        }
    }

    public int CategoryID 
    {
        get
        {
            try
            {
                return int.Parse(hdTrue.Value);
            }
            catch
            {
                return 0;
            }
        }
        set
        {
            hdTrue.Value = value.ToString();
        }
    }

    private ICategoryService categoryService;

    protected void Page_Load(object sender, EventArgs e)
    {
        categoryService = ServiceFactory.Create<ICategoryService>();
        if (!IsPostBack)
        {
            AddTreeView();
            tbCategory.Text = this.categoryName;
        }
    }

    protected void selectedNodeChange(object sender, EventArgs e)
    {
        if (treeCategories.SelectedNode != null)
        {
            hdCategoryId.Value = treeCategories.SelectedNode.Value.ToString();
            hdCategoryName.Value = treeCategories.SelectedNode.Text.ToString();
        }
    }

    private void AddTreeView()
    {
        List<Category> root = categoryService.GetCategories(-1, false);
        foreach (Category item in root)
        {
            System.Web.UI.WebControls.TreeNode node = new System.Web.UI.WebControls.TreeNode();
            node.Text = item.Name;
            node.Value = item.Id.ToString();
            GetNodes(item.Id, node);
            treeCategories.Nodes.Add(node);
        }
    }

    private void GetNodes(int categoryId, System.Web.UI.WebControls.TreeNode parentNode)
    {
        List<Category> childList = categoryService.GetCategories(categoryId, true);
        foreach (Category childItem in childList)
        {
            System.Web.UI.WebControls.TreeNode childNode = new System.Web.UI.WebControls.TreeNode();
            childNode.Text = childItem.Name;
            childNode.Value = childItem.Id.ToString();
            GetNodes(childItem.Id, childNode);
            parentNode.ChildNodes.Add(childNode);
        }
    }
}
